package com.tianya.common.util;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.jsp.PageContext;

import org.apache.commons.lang.time.DateUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class CodeUtils {
	private static Date reflushDate = new Date();
	private static int TIME = 60;
	@SuppressWarnings("unchecked")
	private static List<Map> codeList = new ArrayList<Map>();

	@SuppressWarnings("unchecked")
	public static List<Map> GetCodeList(PageContext pageContext, String code) {
		Date nowDate = new Date();
		Date tmpDate = reflushDate;
		tmpDate = DateUtils.addSeconds(tmpDate, TIME);
		List<Map> retval = new ArrayList<Map>();

		synchronized (codeList) {
			ApplicationContext context = WebApplicationContextUtils
					.getWebApplicationContext(pageContext.getServletContext());
			JdbcTemplate template = (JdbcTemplate) context
					.getBean("jdbcTemplate");
			
			if (0 == codeList.size() || tmpDate.getTime() <= nowDate.getTime()) {
				String sql = "select * from t_Code where flag=0 ";
				sql += "order by code asc,ord asc,id asc";
				List<Map> listTmp = template.queryForList(sql);
				codeList.clear();
				codeList.addAll(listTmp);
			
				//取得
				sql = "select 'T00' CODE,name2,name3,lang  from t_Code where code like 'T__' and flag=0 group by name2,name3,lang, lpad(name2,5,'0'),lpad(name3,5,'0') order by lpad(name2,5,'0'),lpad(name3,5,'0') asc";
				listTmp = template.queryForList(sql);
				codeList.addAll(listTmp);
				reflushDate = nowDate;
			}

		}
		for (int i = 0; i < codeList.size(); i++) {
			if (codeList.get(i).get("CODE").equals(code)) {
				retval.add(codeList.get(i));
			}

		}

		return retval;
	}

	@SuppressWarnings("unchecked")
	public static Map GetCode(PageContext pageContext, String code, String id,String lang) {
		if(Utility.isEmpty(lang)){
			lang = "CN";
		}
		List<Map> tmpList = GetCodeList(pageContext, code);
		for (int i = 0; i < tmpList.size(); i++) {
			if (tmpList.get(i).get("ID").equals(id) && lang.equalsIgnoreCase(tmpList.get(i).get("lang").toString())) {
				return tmpList.get(i);
			}

		}
		return null;
	}
	
	public static void Reset()
	{
		reflushDate = Utility.dateAddDay(new Date(),-1);
	}
}
